# coding=utf-8
# !/usr/bin/python3
# @Time:2021/2/26 9:45 上午
# @Author:wangyun
# @File:utils.py
from django.contrib.auth.backends import ModelBackend
import re
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from itsdangerous import BadData
from .constants import VERIFY_EMAIL_TOKEN_EXPIRES

def check_verify_email_token(token):
    s = Serializer(settings.SECRET_KEY, VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = s.loads(token)
    except BadData:
        return None
    else:
        userid = data.get('userid')
        email = data.get('email')
        try:
            user = User.objects.get(id=userid,email=email)
        except Exception:
            return None
        else:
            return user


def genrate_verify_email_url(user):
    s = Serializer(settings.SECRET_KEY, VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {
        'userid': user.id,
        'email': user.email
    }
    token = s.dumps(data)
    url = settings.EMAIL_VERIFY_URL+'?token='+token.decode()
    return url




def get_user_by_account(account):
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except Exception:
        return None
    else:
        return user


class UserNameMobileBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """

        :param request:
        :param username: 校验是用户名称还是手机号
        :param password:
        :param kwargs:
        :return:
        """
        # if username is None:
        #     username = kwargs.get(UserModel.USERNAME_FIELD)
        # if username is None or password is None:
        #     return
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None

        # try:
        #     user = UserModel._default_manager.get_by_natural_key(username)
        # except UserModel.DoesNotExist:
        #     # Run the default password hasher once to reduce the timing
        #     # difference between an existing and a nonexistent user (#20760).
        #     UserModel().set_password(password)
        # else:
        #     if user.check_password(password) and self.user_can_authenticate(user):
        #         return user
